// patrolnpc.txt
// Creature attacks anything it hates nearby, and spends the rest of its time patrolling a path.
// Once it has won, it returns to its home.
// Memory Cells:
//   Cell 0 - Number of path to follow.
//	 Cell 1 - If 0, just loops around path. If 1, walks to end of path, waits a little, and returns home.
//      If 2, goes to end of path and just stops.
//   Cell 2 - Node if talked to. 0 means no conversation
//   Cell 3,4 - Stuff done flag. If both 0, nothing. Otherwise when this is killed, set to 1.

begincreaturescript;

variables;

short i,target;
short last_abil;
short alive = 0;
short end_count = 0;
short did_walk = 0;
short fleeee = 0;

body;

beginstate INIT_STATE;
	set_name(ME,"Roaming Servile");
	set_level(ME,1);
	set_walk_speed(ME,22);
	
	last_abil = get_current_tick();
	break;

beginstate DEAD_STATE;

break;

beginstate START_STATE;

	if (who_shot_me() >= 0) {
		fleeee = 1;
		}
		
	if (fleeee)
		set_state(5);
	if (get_nearest_party_char(4) >= 0) {
		stop_moving();
		fleeee = 1;
		if (gf(49,4) == 0)
			begin_talk_mode(3);
			else if (gf(49,5) == 0)
				begin_talk_mode(4);
				else {
					print_str_color("Another servile sees you, squeals, and runs away.",3);
					set_state(5);
					}
		}
		
	if (tick_difference(last_abil,get_current_tick()) > 0) {
		last_abil = get_current_tick();
		if (alive < 100)
			alive = alive + 1;
		if ((dist_to_nav_point(ME,0) <= 1) && (alive > 5)) {
			end_count = end_count + 1;
			if ((party_dist_to_nav(0) > 4) && (get_nearest_party_char(10) >= 0)) {
				begin_talk_mode(5);
				}
			if (end_count == 3)
				erase_char(ME);
			}
		}
	
	if (did_walk == 0) {
		follow_path(ME,0,1);
		set_state(4);
		}
		else approach_nav_point(ME,0,1);
		
	if (am_i_doing_action() == FALSE)
		end_combat_turn();
break;

beginstate 3; // attacking
	if (target_ok() == FALSE)
		set_state(START_STATE);
	do_attack();
break;

beginstate 4; // patrol
	if (who_shot_me() >= 0) {
		fleeee = 1;
		}
		
	if (fleeee)
		set_state(5);
	if (get_nearest_party_char(4) >= 0) {
		stop_moving();
		fleeee = 1;
		if (gf(49,4) == 0)
			begin_talk_mode(3);
			else if (gf(49,5) == 0)
				begin_talk_mode(4);
				else {
					print_str_color("Another servile sees you, squeals, and runs away.",3);
					set_state(5);
					}
		}

	if (tick_difference(last_abil,get_current_tick()) > 0) {
		last_abil = get_current_tick();
		if (alive < 100)
			alive = alive + 1;
		}
		
	if (follow_path(ME,0,1) == TRUE) {
		did_walk = 1;
		set_state(START_STATE);
		}

	if ((dist_to_nav_point(ME,0) <= 10) && (alive > 7)) {
		did_walk = 1;
		set_state(START_STATE);
		}		
break;

beginstate 5;
	approach_nav_point(ME,1,2);
	if (dist_to_nav_point(ME,1) <= 1)
		erase_char(ME);
break;

beginstate TALKING_STATE;
	if (get_memory_cell(2) == 0) {
		print_str("Talking: It doesn't respond.");
		}
		else begin_talk_mode(get_memory_cell(2));	
break;